package com.ubhave.powertrackernof1;


import com.ubhave.powertrackernof1.R;

import android.app.AlertDialog;
import android.app.Dialog;

//import android.app.Activity;
import android.support.v4.app.FragmentActivity;
//import android.app.DialogFragment;
import android.support.v4.app.DialogFragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginDialog extends DialogFragment implements OnDismissListener{
	
	LifeGuideConnector lgc;
	SharedPreferences settings;
	SharedPreferences.Editor editor;
	boolean valid;
	LoginDialogListener ldListener;
	
	PowerTrackerSharedPreferenceChangeListener prefChangeListener;
			
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState){
		
		settings=PreferenceManager.getDefaultSharedPreferences(PowerTrackerApplication.getContext());
		editor=settings.edit();
	    lgc=new LifeGuideConnector(settings);
	    
	    prefChangeListener = new PowerTrackerSharedPreferenceChangeListener();
        settings.registerOnSharedPreferenceChangeListener(prefChangeListener);
        //Log.i("POWeR Tracker Special: ", "Dialog: PrefListen On");
	    
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		LayoutInflater inflater = getActivity().getLayoutInflater();
		
		//final Activity act = getActivity();
		final FragmentActivity act = getActivity();
		ldListener = (LoginDialogListener) act;

	    // Inflate and set the layout for the dialog
	    // Pass null as the parent view because its going in the dialog layout
		
		final View dialogView = inflater.inflate(R.layout.logindialog, null);
		//Log.i("POWeR Tracker Special: ", "LOGIN TEST");
						
		if(getArguments()!=null&&getArguments().containsKey("error")){
			TextView errortv=(TextView)dialogView.findViewById(R.id.logindialogerror);
			errortv.setText(getArguments().getString("error"));
		}
		
	    builder.setView(dialogView)
	    // Add action buttons
	       	.setPositiveButton("Log in", new DialogInterface.OnClickListener() {
	           	@Override
	           	public void onClick(DialogInterface dialog, int id) {
	           	   	Log.i("POWeR Tracker: ", "Making Login");
	           	   	final EditText unedit=(EditText)dialogView.findViewById(R.id.logindialogusername);
	           	   	final EditText pwedit=(EditText)dialogView.findViewById(R.id.logindialogpassword);
	           	   	           	   	
	           	   	class AsyncLogin extends AsyncTask{

	           	   		@Override
	       				protected Object doInBackground(Object... params) {
	           	   			String un = unedit.getText().toString();
	           	   			boolean result = lgc.loginPost(unedit.getText().toString(), pwedit.getText().toString(), settings.getString("LifeGuideInterventionId", ""));
	           	   			
	           	   			
	           	   			
	           	   			if(!result){
	           	  	     		DialogFragment dialog = new LoginDialog();
	           	  	     		Bundle errorBundle = new Bundle();
	           	  	     		ConnectivityManager cm = (ConnectivityManager)PowerTrackerApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
	           	 		   		NetworkInfo ni = cm.getActiveNetworkInfo();
	           	 		   		if(ni==null)
	           	 		   			errorBundle.putString("error", "You have no internet connection, please establish an internet connection before logging in.");
	           	 		   		else
	           	 		   			errorBundle.putString("error", "Invalid Username or Password");
	           	  	     		dialog.setArguments(errorBundle);
	           	  	     		//dialog.show(getFragmentManager(), "LoginDialog");
	           	  	     		dialog.show(act.getSupportFragmentManager(), "LoginDialog");
	           	  	     		
	           	  	     	}
	           	   			else{
	           	   				editor.putString("LifeGuideUser", unedit.getText().toString());
	           	   				editor.commit();
	           	   				ldListener.onLoginDialogPositiveClick(); 
	           	   			}
	           	   				
	           	   			return this;
	       				}
	           	   		
		           	   	protected void onPostExecute(Object result) {
		           	   		settings.unregisterOnSharedPreferenceChangeListener(prefChangeListener);
		           	   		//Log.i("POWeR Tracker Special: ", "Dialog: PrefListen Off");
		    		    }
	           	   	}
	           	   	
	           	   	
	           	   	new AsyncLogin().execute(this);
	           	   	
	           	}
	       	})
	       	.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	       		public void onClick(DialogInterface dialog, int id) {
	       			Toast.makeText(PowerTrackerApplication.getContext(), "Login Dialog Cancelled - Warning: POWeR Login Details are required to use POWeR Tracker", Toast.LENGTH_LONG).show();
	       			ldListener.onLoginDialogNegativeClick();     			
	       			LoginDialog.this.getDialog().cancel();
	       		}
	       	});      
	    return builder.create();
	}
	
	@Override
	public void onStop(){
		super.onStop();
		
	}
	
	
	
	
}